//
//  DDErandsApplyListViewController.m
//  KIASupervisory
//
//  Created by tan_xin on 14-7-1.
//  Copyright (c) 2014年 MyCompany. All rights reserved.
//

#import "DDErandsApplyListViewController.h"
#import "ApplyErandsViewController.h"
#import "StoreProblemListViewController.h"
#import "ErandReportViewController.h"
#import "MTStatusBarOverlay.h"

@interface DDErandsApplyListViewController ()

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (weak, nonatomic) IBOutlet UIButton *selectCellBtn;
@property (weak, nonatomic) IBOutlet UILabel *userNameLbl;
@property (weak, nonatomic) IBOutlet UILabel *userIDLbl;
@property (weak, nonatomic) IBOutlet UILabel *dateLbl;
@property (weak, nonatomic) IBOutlet UILabel *dateEndLbl;
@property (weak, nonatomic) IBOutlet UILabel *agencyNameLbl;
@property (weak, nonatomic) IBOutlet UILabel *agencyCodeLbl;
@property (weak, nonatomic) IBOutlet UILabel *reasonLbl;
@property (weak, nonatomic) IBOutlet UIButton *statusBtn;

@property (weak, nonatomic) IBOutlet UIImageView *deleteIcon;
@property (weak, nonatomic) IBOutlet UILabel *deleteLbl;
@property (weak, nonatomic) IBOutlet UIButton *deleteBtn;
@property (weak, nonatomic) IBOutlet UIImageView *submitIcon;
@property (weak, nonatomic) IBOutlet UILabel *submitLbl;
@property (weak, nonatomic) IBOutlet UIButton *submitBtn;

@property (nonatomic, strong) NSMutableDictionary *selectedRowDict; //选中的行
@property (nonatomic, assign) BOOL hasSelectedRow; //是否有选中的行

@property (nonatomic ,strong) NSMutableArray *applyList; //出差申请列表
@property (nonatomic, assign) NSInteger selectedRow;

- (IBAction)deleteErandAction:(id)sender;
- (IBAction)submitApplyAction:(id)sender;


@end

@implementation DDErandsApplyListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.selectedRowDict = [NSMutableDictionary dictionary];
    self.hasSelectedRow = NO;
    
    self.applyList = [NSMutableArray array];
    
    self.networkManager = [[NetworkManager alloc] init];
    
    [self initHUD];
    
    self.selectedRow = -1;
    
}

- (void)viewWillAppear:(BOOL)animated {
    
    self.showLeftBtn = YES;
    self.showRightBtn = YES;
    
    self.title = @"出差申请";
    [super viewWillAppear:animated];
    
//    self.navigationController.navigationBarHidden = YES;
    
    [self.rightBtn setBackgroundImage:[UIImage imageNamed:@"Navigationbar_btn_新增_n.png"] forState:UIControlStateNormal];
    [self.rightBtn setBackgroundImage:[UIImage imageNamed:@"Navigationbar_btn_新增_p.png"] forState:UIControlStateHighlighted];
    
    [self.selectedRowDict removeAllObjects];
    [self updateBottomBarStatusWithSelected:NO];
    
    [self performSelector:@selector(getErandsApplyList) withObject:nil afterDelay:0.3];
}

- (void)refreshViewByReloadData {
    [self getErandsApplyList];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)leftNavItemAction:(id)sender {
    AppDelegate *dele = [AppDelegate sharedDelegate];
    DDMenuController *menuVC = dele.ddLeftMenu;
    [menuVC showLeft:nil];
}

- (void)rightNavItemAction:(id)sender {
    ApplyErandsViewController *applyNewVC = (ApplyErandsViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"ApplyErandsViewController"];
    applyNewVC.canEdit = YES;
    [self.navigationController pushViewController:applyNewVC animated:YES];
}

//查询出差申请列表
- (void)getErandsApplyList {
    if (!self.isRefreshing) {
        UserInfo *user = [UserInfo instance];
        NSString *gonghao = [user.info objectForKeyOrNil:@"gh"];
        NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                               gonghao,@"gh", nil];
        [self.networkManager requestWithMethod:workApplyList parameter:param delegate:self];
        [self.HUD show:YES];
        self.isRefreshing = YES;
    }
}

//删除申请
- (IBAction)deleteErandAction:(id)sender {
    if (!self.hasSelectedRow) {
        return;
    }
    
    BOOL valid = YES;
    NSString *erandIDList = @"";
    
    for (int i = 0; i < [self.applyList count]; i ++) {
        NSNumber *key = [NSNumber numberWithInteger:i];
        BOOL selected = [[self.selectedRowDict objectForKeyOrNil:key] boolValue];
        if (selected) {
            NSDictionary *erandInfo = [self.applyList objectAtIndex:i];
            
            BOOL rejected = [[erandInfo objectForKeyOrNil:@"sfbh"] boolValue]; //是否驳回
            BOOL passed = [[erandInfo objectForKeyOrNil:@"shzt"] boolValue]; //申请状态
            BOOL submitted = [[erandInfo objectForKey:@"sftj"] boolValue]; //是否已经提交
            if (passed || (!rejected && !passed && submitted)) {
                valid = NO;
                break;
            }
            
            NSString *ID = [erandInfo objectForKeyOrNil:@"id"];
            if ([erandIDList length] > 0) {
                erandIDList = [erandIDList stringByAppendingFormat:@",%@",ID];
            } else {
                erandIDList = [erandIDList stringByAppendingFormat:@"%@",ID];
            }
        }
    }
    
    if (valid) {
        if ([erandIDList length] > 0) {
            NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                                   erandIDList,@"id", nil];
            [self.networkManager requestWithMethod:deleteWorkApply parameter:param delegate:self];
            [self.HUD show:YES];
        }
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"不能删除已通过和待审核状态的出差申请"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    }
}

- (IBAction)submitApplyAction:(id)sender {
    
    if (!self.hasSelectedRow) {
        return;
    }
    
    BOOL valid = YES;
    
    NSString *erandIDList = @"";
    
    for (int i = 0; i < [self.applyList count]; i ++) {
        NSNumber *key = [NSNumber numberWithInteger:i];
        BOOL selected = [[self.selectedRowDict objectForKeyOrNil:key] boolValue];
        if (selected) {
            NSDictionary *erandInfo = [self.applyList objectAtIndex:i];
            
            BOOL rejected = [[erandInfo objectForKeyOrNil:@"sfbh"] boolValue]; //是否驳回
            BOOL passed = [[erandInfo objectForKeyOrNil:@"shzt"] boolValue]; //申请状态
            BOOL submitted = [[erandInfo objectForKey:@"sftj"] boolValue]; //是否已经提交
            if (rejected || passed || submitted) {
                valid = NO;
                break;
            }
            
            NSString *ID = [erandInfo objectForKeyOrNil:@"id"];
            if ([erandIDList length] > 0) {
                erandIDList = [erandIDList stringByAppendingFormat:@",%@",ID];
            } else {
                erandIDList = [erandIDList stringByAppendingFormat:@"%@",ID];
            }
        }
    }
    
    if (valid) {
        if ([erandIDList length] > 0) {
            UserInfo *user = [UserInfo instance];
            NSString *gonghao = [user.info objectForKeyOrNil:@"gh"];
            NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                                   gonghao,@"gh",
                                   erandIDList,@"id",
                                   nil];
            [self.networkManager requestWithMethod:workApplySubmit parameter:param delegate:self];
            [self.HUD show:YES];
        }
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"只能提交未通过状态的出差申请"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    }
}

#pragma mark - IBAction methods
- (void)selectRowAction:(id)sender event:(id)event {
    NSSet *touches = [event allTouches];
	UITouch *touch = [touches anyObject];
	CGPoint currentTouchPosition = [touch locationInView:self.tableView];
	NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition];
	if (indexPath == nil) {
		return;
	}
    int row = indexPath.row;
    NSLog(@"!!!!!!!!!!11111");
    UIButton *btn = (UIButton *)sender;
    NSInteger tag = btn.tag;
    
    if (tag == 100) { //选中、取消选中行
        NSLog(@"!!!!!!!!!!222222");
        BOOL selected = YES;
        if ([self.selectedRowDict objectForKeyOrNil:[NSNumber numberWithInt:row]]) {
            BOOL value = [[self.selectedRowDict objectForKeyOrNil:[NSNumber numberWithInt:row]] boolValue];
            selected = !value;
        }
        [self.selectedRowDict setObject:[NSNumber numberWithBool:selected] forKey:[NSNumber numberWithInt:row]];
        
        BOOL hasSelected = NO;
        NSArray *keys = [self.selectedRowDict allKeys];
        for (int i = 0; i < [keys count]; i ++) {
            NSString *key = [keys objectAtIndex:i];
            BOOL value = [[self.selectedRowDict objectForKeyOrNil:key] boolValue];
            if (value) {
                hasSelected = YES;
                break;
            }
        }
        
        self.hasSelectedRow = hasSelected;
        
        [self updateBottomBarStatusWithSelected:hasSelected];
        
        [self.tableView reloadData];
    } else if (tag == 107) { //状态按钮

        self.selectedRow = row;
        
        if ([self.applyList count] > row) {
            NSDictionary *cellData = [self.applyList objectAtIndex:row];
            
            BOOL rejected = [[cellData objectForKeyOrNil:@"sfbh"] boolValue]; //是否驳回
            
            if (rejected) { //驳回状态
                NSString *reason = [cellData objectForKeyOrNil:@"bhly"];
                if ([reason length] > 0) {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"驳回理由"
                                                                    message:reason
                                                                   delegate:self
                                                          cancelButtonTitle:@"修改"
                                                          otherButtonTitles:@"确定",nil];
                    alert.tag = 1007;
                    [alert show];
                } else {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"驳回理由"
                                                                    message:@"未知理由驳回"
                                                                   delegate:self
                                                          cancelButtonTitle:@"修改"
                                                          otherButtonTitles:@"确定",nil];
                    alert.tag = 1007;
                    [alert show];
                }
            }
        }
    }
    
}

- (void)updateBottomBarStatusWithSelected:(BOOL)hasSelected {
    
    self.deleteBtn.enabled = hasSelected;
    self.submitBtn.enabled = hasSelected;
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 1007) {
        if (buttonIndex == alertView.cancelButtonIndex) {
            if ([self.applyList count] > self.selectedRow && 0 <= self.selectedRow) {
                NSDictionary *cellData = [self.applyList objectAtIndex:self.selectedRow];
                ApplyErandsViewController *applyVC = (ApplyErandsViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"ApplyErandsViewController"];
                applyVC.erandInfo = [NSMutableDictionary dictionaryWithDictionary:cellData];
                applyVC.canEdit = YES;
                [self.navigationController pushViewController:applyVC animated:YES];
            }
        }
    }
}

#pragma mark - NetworkManagerDelegate
- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFinishedWithResult:(id)data {
    [self.HUD hide:YES];
    self.isRefreshing = NO;
    [self endRefresh];
     NSLog(@"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
    if ([data isKindOfClass:[NSDictionary class]]) {
        int code = [[data objectForKeyOrNil:@"code"] integerValue];
        if (code == 0) { //请求成功
            if ([data count] > 0) {
                id dataObject = [data objectForKeyOrNil:@"data"];
                
                if (methodId == workApplyList) { //出差申请列表
                    [self.applyList removeAllObjects];
                    if ([dataObject isKindOfClass:[NSDictionary class]]) {
                        NSArray *results = [dataObject objectForKeyOrNil:@"workApplys"];
                        if (![results isKindOfClass:[NSNull class]] && [results count] > 0) {
                            [self.applyList  addObjectsFromArray:results];
                        }
                    }
                    
                    [self.tableView reloadData];
                    
                } else if (methodId == workApplySubmit) { //提交申请
                    
                    NSInteger resultCode = [[dataObject objectForKey:@"result"] integerValue];
                    if (resultCode == 0) { //提交成功
                        
                        [self showAlertViewWithMessage:@"出差申请提交成功"];
                        
//                        MTStatusBarOverlay *overlay = [MTStatusBarOverlay sharedInstance];
//                        overlay.animation = MTStatusBarOverlayAnimationFallDown;
//                        overlay.detailViewMode = MTDetailViewModeDetailText;
//                        overlay.delegate = nil;
//                        overlay.progress = 0.0;
//                        [overlay postFinishMessage:@"出差申请提交成功！" duration:1.6 animated:YES];
//                        overlay.progress = 1.8;

                        [self performSelector:@selector(refreshView) withObject:nil afterDelay:0.9];

                    }
                } else if (methodId == deleteWorkApply) { //删除出差申请
                    
                    NSInteger resultCode = [[dataObject objectForKey:@"result"] integerValue];
                    if (resultCode == 0) { //删除成功
                        
                        NSString *msg = @"出差申请删除成功";
                        [self showAlertViewWithMessage:msg];
                        
//                        MTStatusBarOverlay *overlay = [MTStatusBarOverlay sharedInstance];
//                        overlay.animation = MTStatusBarOverlayAnimationFallDown;
//                        overlay.detailViewMode = MTDetailViewModeDetailText;
//                        overlay.delegate = nil;
//                        overlay.progress = 0.0;
//                        [overlay postFinishMessage:@"出差申请删除成功！" duration:1.6 animated:YES];
//                        overlay.progress = 1.8;
                        
                        [self performSelector:@selector(refreshView) withObject:nil afterDelay:0.9];
                        
                        
                    }
                } else if (methodId == checkPc){
                    NSInteger resultCode = [[dataObject objectForKey:@"result"] integerValue];
                    NSInteger row = [[dataObject objectForKey:@"row"] integerValue];
                    if (resultCode == 1) {
                        NSString *msg = @"请先处理上一个批次的任务";
                        [self showAlertViewWithMessage:msg];
                    } else {
                        StoreProblemListViewController *problemVC = (StoreProblemListViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"DudaoStoreProblemList"];
                         NSDictionary *cellData = [self.applyList objectAtIndex:row];
                         problemVC.erandInfo = [NSMutableDictionary dictionaryWithDictionary:cellData];
                 
                         problemVC.sfbg =[[cellData objectForKey:@"sfbg"] boolValue]; //是否变更
                          [self.navigationController pushViewController:problemVC animated:YES];
                    }
                     [self performSelector:@selector(refreshView) withObject:nil afterDelay:0.9];
                }
            }
        }
    }
    
}

- (void)refreshView {
    for (int i = 0; i < [self.selectedRowDict count]; i ++) {
        [self.selectedRowDict setObject:[NSNumber numberWithBool:NO] forKey:[NSNumber numberWithInt:i]];
    }
    [self updateBottomBarStatusWithSelected:NO];
    
    [self getErandsApplyList];
}

- (void)showErandReport {
    ErandReportViewController *reportVC = (ErandReportViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"ErandReportView"];
    int selectedRow = 0;
    NSArray *keys = [self.selectedRowDict allKeys];
    for (int i = 0; i < [keys count]; i ++) {
        NSString *key = [keys objectAtIndex:i];
        if ([[self.selectedRowDict objectForKey:key] boolValue]) {
            selectedRow = [key integerValue];
            break;
        }
    }
    if ([self.applyList count] > selectedRow) {
        NSDictionary *applyInfo = [self.applyList objectAtIndex:selectedRow];
        reportVC.applyInfo = applyInfo;
    }
    reportVC.fromLeader = NO;
    [self.navigationController pushViewController:reportVC animated:YES];
}

- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFailedWithError:(NSError *)error {
    
    [self.HUD hide:YES];
    [self endRefresh];
    self.isRefreshing = NO;
    
    NSDictionary *errorInfo = error.userInfo;
    NSString *msg = [errorInfo objectForKeyOrNil:@"errorMsg"];
    
    NSInteger code = error.code;
    if (code != 1) {
        if ([msg length] == 0) {
            if (methodId == workApplyList) {
                msg = @"出差申请列表获取失败，请稍后重试";
            } else if (methodId == workApplySubmit) {
                msg = @"出差申请提交失败，请稍后重试";
            } else if (methodId == deleteWorkApply) {
                msg = @"出差申请删除失败，请稍候重试";
            } else {
                msg = @"操作失败，请稍后重试";
            }
        }
    }
    
    if ([msg length] > 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:msg
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    }
}

#pragma mark - UITableViewDataSource methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    [self endRefresh];
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.applyList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"ErrandsApplyCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        
    }
    UIButton *selectBtn = (UIButton *)[cell.contentView viewWithTag:100];
    UILabel *userNameLbl = (UILabel *)[cell.contentView viewWithTag:101];
    UILabel *userIDLbl = (UILabel *)[cell.contentView viewWithTag:102];
    UILabel *dateLbl = (UILabel *)[cell.contentView viewWithTag:103];
    UILabel *agencyNameLbl = (UILabel *)[cell.contentView viewWithTag:104];
    UILabel *agencyCodeLbl = (UILabel *)[cell.contentView viewWithTag:105];
    UILabel *reasonLbl = (UILabel *)[cell.contentView viewWithTag:106];
    UIButton *statusBtn = (UIButton *)[cell.contentView viewWithTag:107];
    

    [selectBtn addTarget:self action:@selector(selectRowAction:event:) forControlEvents:UIControlEventTouchUpInside];
    [statusBtn addTarget:self action:@selector(selectRowAction:event:) forControlEvents:UIControlEventTouchUpInside];
    
    NSInteger row = indexPath.row;
    if ([self.selectedRowDict objectForKeyOrNil:[NSNumber numberWithInt:row]]) {
        BOOL selected = [[self.selectedRowDict objectForKeyOrNil:[NSNumber numberWithInt:row]] boolValue];
        if (selected) {
            [selectBtn setBackgroundImage:[UIImage imageNamed:@"勾选btn_p.png"] forState:UIControlStateNormal];
        } else {
            [selectBtn setBackgroundImage:[UIImage imageNamed:@"勾选btn_n.png"] forState:UIControlStateNormal];
        }
    } else {
        [selectBtn setBackgroundImage:[UIImage imageNamed:@"勾选btn_n.png"] forState:UIControlStateNormal];
    }
    
    if ([self.applyList count] > row) {
        NSDictionary *cellData = [self.applyList objectAtIndex:row];
        
        NSString *dudaoName = [cellData objectForKeyOrNil:@"xm"];
        NSString *dudaoCode = [cellData objectForKeyOrNil:@"gh"];
        NSString *merchantName = [cellData objectForKeyOrNil:@"jxsmc"];
        NSString *merchantCode = [cellData objectForKeyOrNil:@"jxsdm"];
        NSString *merchantbgName = [cellData objectForKeyOrNil:@"bgjxsmc"];
        NSString *merchantbgCode = [cellData objectForKeyOrNil:@"bgjxsdm"];
        NSString *reason = [cellData objectForKeyOrNil:@"ccmd"];
        NSString *bgreason = [cellData objectForKeyOrNil:@"bgmd"];
        NSString *time = [cellData objectForKeyOrNil:@"ccsj"];
     
        if ([dudaoName isKindOfClass:[NSNull class]]) {
            dudaoName = @"";
        }
        if ([dudaoCode isKindOfClass:[NSNull class]]) {
            dudaoCode = @"";
        }
        if ([merchantName isKindOfClass:[NSNull class]]) {
            merchantName = @"";
        }
        if ([merchantCode isKindOfClass:[NSNull class]]) {
            merchantCode = @"";
        }
        if ([reason isKindOfClass:[NSNull class]]) {
            reason = @"";
        }
        if ([time isKindOfClass:[NSNull class]]) {
            time = @"";
        }
        BOOL sfbg = [[cellData objectForKey:@"sfbg"] boolValue]; //是否变更
        BOOL bgshzt = [[cellData objectForKey:@"bgshzt"] boolValue]; //变更审核状态
        
        
        userNameLbl.text = dudaoName;
        userIDLbl.text = dudaoCode;
        agencyNameLbl.text = merchantName;
        agencyCodeLbl.text = merchantCode;
        reasonLbl.text = reason;
        dateLbl.text = time;

        BOOL rejected = [[cellData objectForKeyOrNil:@"sfbh"] boolValue]; //是否驳回
        BOOL passed = [[cellData objectForKeyOrNil:@"shzt"] boolValue]; //申请状态
        BOOL submitted = [[cellData objectForKey:@"sftj"] boolValue]; //是否已经提交
        NSLog(@"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@11111@@@@%d",sfbg);
        NSLog(@"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@11111@@@@%d",bgshzt);
        NSLog(@"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@11111@@@@%d",rejected);
        NSLog(@"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@11111@@@@%d",passed);
        NSLog(@"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@11111@@@@%d",submitted);
        
        if (rejected) {
            [statusBtn setTitle:@"驳回" forState:UIControlStateNormal];
            [statusBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [statusBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
            [statusBtn setBackgroundImage:[UIImage imageNamed:@"tip_驳回.png"] forState:UIControlStateNormal];
        } else {
            if (passed) { //通过
                if(sfbg && !bgshzt){
                    agencyNameLbl.text = merchantbgName;
                    agencyCodeLbl.text = merchantbgCode;
                    reasonLbl.text = bgreason;
                    NSString *bgldxm = [cellData objectForKeyOrNil:@"bgldxm"];
                    NSString *statusText = [@"待审核\n" stringByAppendingString:bgldxm];
                    [statusBtn setTitle:statusText forState:UIControlStateNormal];
                    [statusBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                    [statusBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
                    [statusBtn setBackgroundImage:[UIImage imageNamed:@"tip_待审核.png"] forState:UIControlStateNormal];
                    statusBtn.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
                    statusBtn.frame = CGRectMake(223, 25, 66, 35);
                } else {
                    if(sfbg && bgshzt){
                        agencyNameLbl.text = merchantbgName;
                        agencyCodeLbl.text = merchantbgCode;
                        reasonLbl.text = bgreason;
                    }
                    [statusBtn setTitle:@"已通过" forState:UIControlStateNormal];
                    [statusBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                    [statusBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
                    [statusBtn setBackgroundImage:[UIImage imageNamed:@"tip_通过.png"] forState:UIControlStateNormal];
                    statusBtn.frame = CGRectMake(223, 35, 66, 20);
                    
                }
                
            } else if (submitted) { //待审核
                NSString *ldxm = [cellData objectForKeyOrNil:@"ldxm"];
                NSString *statusText = [@"待审核\n" stringByAppendingString:ldxm];
                [statusBtn setTitle:statusText forState:UIControlStateNormal];
                [statusBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                [statusBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
                [statusBtn setBackgroundImage:[UIImage imageNamed:@"tip_待审核.png"] forState:UIControlStateNormal];
                statusBtn.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
                statusBtn.frame = CGRectMake(223, 32, 66, 40);
            } else { //未通过
                [statusBtn setTitle:@"未通过" forState:UIControlStateNormal];
                [statusBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                [statusBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
                [statusBtn setBackgroundImage:[UIImage imageNamed:@"tip_未通过.png"] forState:UIControlStateNormal];
            }
        }
    }
    return cell;
    
}

#pragma mark - UITableViewDelegate methods
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = [indexPath row];
    NSDictionary *cellData = [self.applyList objectAtIndex:row];
    BOOL rejected = [[cellData objectForKeyOrNil:@"sfbh"] boolValue]; //是否驳回
    BOOL passed = [[cellData objectForKeyOrNil:@"shzt"] boolValue]; //申请状态
    BOOL submitted = [[cellData objectForKey:@"sftj"] boolValue]; //是否已经提交
    if (!rejected && submitted && !passed) {
        return 75.0;
    }else
        return 60.0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSInteger row = indexPath.row;
    self.selectedRow = row;
    
    if ([self.applyList count] > row) {
        NSDictionary *cellData = [self.applyList objectAtIndex:row];
        BOOL passed = [[cellData objectForKeyOrNil:@"shzt"] boolValue]; //申请状态
        
        if (passed) { //已通过，进入临店项目
            BOOL finished = [[cellData objectForKeyOrNil:@"sfwc"] boolValue]; //是否已完成
            BOOL sfbg = [[cellData objectForKeyOrNil:@"sfbg"] boolValue]; //是否变更
            BOOL bgshzt = [[cellData objectForKeyOrNil:@"bgshzt"] boolValue]; //变更审核状态
            if (finished) { //已完成，显示出差报告
                if ([self.applyList count] > row) {
                    ErandReportViewController *reportVC = (ErandReportViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"ErandReportView"];
                    NSDictionary *applyInfo = [self.applyList objectAtIndex:row];
                    reportVC.applyInfo = applyInfo;
                    [self.navigationController pushViewController:reportVC animated:YES];
                }
            } else if(sfbg && !bgshzt){ //未完成 已变更未审核
                
            } else { //未完成，进入临店项目列表
                UserInfo *user = [UserInfo instance];
                NSString *gonghao = [user.info objectForKeyOrNil:@"gh"];
                NSDictionary *cellData = [self.applyList objectAtIndex:row];
                NSString *pc = [cellData objectForKeyOrNil:@"pc"];
                NSString *rowId =[NSString stringWithFormat: @"%d", row];
                NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                                       gonghao,@"gh",pc,@"pc",rowId,@"row",nil];
                
                [self.networkManager requestWithMethod:checkPc parameter:param delegate:self];

                
            }
        } else {
            ApplyErandsViewController *applyVC = (ApplyErandsViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"ApplyErandsViewController"];
            
            BOOL rejected = [[cellData objectForKeyOrNil:@"sfbh"] boolValue]; //是否驳回
            BOOL submitted = [[cellData objectForKey:@"sftj"] boolValue]; //是否已经提交
            
            if (submitted && !rejected && !passed) { //待审核状态
                applyVC.canEdit = NO;
            } else {
                applyVC.canEdit = YES;
            }
            
            applyVC.erandInfo = [NSMutableDictionary dictionaryWithDictionary:cellData];
            [self.navigationController pushViewController:applyVC animated:YES];
        }
    }
    
}

@end
